package com.example.jucdemo.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfig {
    /**
     * 核心线程数
     */
    private static final int corePoolSize = Runtime.getRuntime().availableProcessors() + 1;

    /**
     * 最大线程数 避免内存交换 设置为核心核心线程数
     */
    private static final int maximumPoolSize = corePoolSize;

    /**
     * 最大空闲时间
     */
    private static final long keepAliveTime = 3;

    /**
     * 最大空闲时间单位
     */
    private static final TimeUnit unit = TimeUnit.MINUTES;

    /**
     * 使用有界队列，避免内存溢出
     */
    private static final BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>(500);

    /**
     * 线程工厂，这里我们使用可命名的线程工厂，方便业务区分以及生产问题排查。
     */
    private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();

    /**
     * 拒绝策略 根据业务选择或者自定义；这里选择丢弃策略
     */
    private static final RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize
                , maximumPoolSize
                , keepAliveTime
                , unit
                , workQueue
                , threadFactory
                , handler);
        // 核心线程预热
        threadPoolExecutor.prestartAllCoreThreads();
        return threadPoolExecutor;
    }

}
